using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;

namespace Fanfou
{
    /// <summary>
    /// HeyRice class
    /// </summary>
    partial class HeyRice
    {
        #region Variables
        static string userName = null;
        static string base64UserInfo = null;
        static bool isLogin = false;
        #endregion

        /// <summary>
        /// Show home screen
        /// </summary>
        private static void ShowBasicScreen()
        {
            //Console.WindowWidth = 80;
            //Console.BufferWidth = 80;
            
            Console.Clear();
            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine(AppString.SYSTEM_TITLE);
            Console.WriteLine("|                                                        |");
            Console.WriteLine("|             by http://liyao.me  or @Heiyoo             |");
            Console.WriteLine("----------------------------------------------------------");
            Console.WriteLine();

            if (isLogin)
            {
                Console.WriteLine(AppString.SYSTEM_CURRENT_USER + userName);
            }
        }

        /// <summary>
        /// Send POST request and get the server response
        /// </summary>
        /// <param name="parameters">POST parameters</param>
        /// <param name="apiUrl">API Url</param>
        /// <returns>Server response</returns>
        private static HttpWebResponse PostAndRecieve(string parameters, string apiUrl)
        {
            // Construct the HTTP POST request
            byte[] paraBytes = Encoding.UTF8.GetBytes(parameters);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            request.ServicePoint.Expect100Continue = false;
            request.Headers.Add("Authorization", "Basic " + base64UserInfo);
            request.ContentLength = paraBytes.Length;

            // Send HTTP POST request
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(paraBytes, 0, paraBytes.Length);
            requestStream.Close();

            // Get server response
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            string responseString = sr.ReadToEnd();
            sr.Close();
            stream.Close();

            return response;
        }

        /// <summary>
        /// Send GET request and get the server response
        /// </summary>
        /// <param name="apiUrl">API Url</param>
        /// <returns>Server response</returns>
        private static HttpWebResponse GetAndReceive(string apiUrl)
        {
            // Construct the HTTP GET request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "GET";
            request.Headers.Add("Authorization", "Basic " + base64UserInfo);
            HttpWebResponse response = null;

            // Get server response
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
                response = (HttpWebResponse)ex.Response;
            }
            return response;
        }

        /// <summary>
        /// Parse and list friends
        /// </summary>
        /// <param name="xmlResponse">Server response in XML</param>
        private static void ParseFriends(XmlDocument xmlResponse)
        {
            // Get the friend ID and name
            XmlNodeList idList = xmlResponse.GetElementsByTagName("id");
            XmlNodeList nameList = xmlResponse.GetElementsByTagName("name");

            // Output friend list
            int i = 0;
            foreach (XmlNode node in nameList)
            {
                Console.WriteLine((i + 1).ToString() + "  " + idList[i].InnerText + "  " + nameList[i].InnerText);
                Console.WriteLine();
                i++;
            }
        }

        /// <summary>
        /// Parse and output messages
        /// </summary>
        /// <param name="xmlResponse">Server response in XML</param>
        private static void ParsePosts(XmlDocument xmlResponse)
        {
            // Get basic information of messages
            XmlNodeList textList = xmlResponse.GetElementsByTagName("text");
            XmlNodeList timeList = xmlResponse.GetElementsByTagName("created_at");
            XmlNodeList nameList = xmlResponse.GetElementsByTagName("name");

            int i = 0;
            foreach (XmlNode node in textList)
            {
                // Output messages
                Display.Write(nameList[i].InnerXml, ConsoleColor.Yellow);
                Display.Write(" " + GetShortTimeStamp(timeList[i * 2].InnerXml), ConsoleColor.Gray);
                Display.Write(": ", ConsoleColor.DarkCyan);
                if (textList[i].InnerText.Contains("@"))
                {
                    Display.WriteLine(textList[i].InnerText, true);
                }
                else
                {
                    Display.WriteLine(textList[i].InnerText);
                }
                Display.WriteLine();

                i++;
            }
        }

        /// <summary>
        /// Get the time stamp in short format
        /// </summary>
        /// <param name="timeStamp">Long time in server response</param>
        /// <returns>Short time stamp</returns>
        private static string GetShortTimeStamp(string timeStamp)
        {
            string shortTimeStamp = null;

            #region Get time details
            // Cut the week day information
            shortTimeStamp = timeStamp.Substring(timeStamp.IndexOf(" ") + 1);
            // Cut the time zone information
            shortTimeStamp = shortTimeStamp.Substring(0, shortTimeStamp.IndexOf("+") - 1);

            string year = timeStamp.Substring(timeStamp.Length - 4, 4);
            string month = shortTimeStamp.Substring(0, shortTimeStamp.IndexOf(" "));
            shortTimeStamp = shortTimeStamp.Substring(shortTimeStamp.IndexOf(" ") + 1);
            string date = shortTimeStamp.Substring(0, shortTimeStamp.IndexOf(" "));
            shortTimeStamp = shortTimeStamp.Substring(shortTimeStamp.IndexOf(" ") + 1);
            string hour = shortTimeStamp.Substring(0, shortTimeStamp.IndexOf(":"));
            shortTimeStamp = shortTimeStamp.Substring(shortTimeStamp.IndexOf(":") + 1);
            string minute = shortTimeStamp.Substring(0, shortTimeStamp.IndexOf(":"));
            shortTimeStamp = shortTimeStamp.Substring(shortTimeStamp.IndexOf(":") + 1);
            string second = shortTimeStamp.Substring(shortTimeStamp.IndexOf(":") + 1);
            #endregion

            #region Get month detail in integer.
            int intMonth = 0;
            switch (month)
            {
                case ("Jan"):
                    intMonth = 1;
                    break;
                case ("Feb"):
                    intMonth = 2;
                    break;
                case ("Mar"):
                    intMonth = 3;
                    break;
                case ("Apr"):
                    intMonth = 4;
                    break;
                case ("May"):
                    intMonth = 5;
                    break;
                case ("June"):
                    intMonth = 6;
                    break;
                case ("Jun"):
                    intMonth = 6;
                    break;
                case ("July"):
                    intMonth = 7;
                    break;
                case ("Jul"):
                    intMonth = 7;
                    break;
                case ("Aug"):
                    intMonth = 8;
                    break;
                case ("Sept"):
                    intMonth = 9;
                    break;
                case ("Sep"):
                    intMonth = 9;
                    break;
                case ("Oct"):
                    intMonth = 10;
                    break;
                case ("Nov"):
                    intMonth = 11;
                    break;
                case ("Dec"):
                    intMonth = 12;
                    break;
                default:
                    intMonth = 0;
                    break;
            }
            #endregion

            DateTime time = new DateTime(Int32.Parse(year), intMonth, Int32.Parse(date), Int32.Parse(hour), Int32.Parse(minute), Int32.Parse(second), DateTimeKind.Utc);

            return time.ToLocalTime().ToString("MM/dd HH:mm");
        }
    }
}
